package com.microblog.microblogsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.microblog.microblogsystem.constant.JwtClaimsConstant;
import com.microblog.microblogsystem.constant.MessageConstant;
import com.microblog.microblogsystem.domain.dto.UserLoginDTO;
import com.microblog.microblogsystem.domain.po.User;
import com.microblog.microblogsystem.domain.vo.UserLoginVO;
import com.microblog.microblogsystem.exception.BaseException;
import com.microblog.microblogsystem.mapper.UserMapper;
import com.microblog.microblogsystem.properties.JwtProperties;
import com.microblog.microblogsystem.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microblog.microblogsystem.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-06-28
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final JwtProperties jwtProperties;


    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        User user = this.lambdaQuery()
                        .eq(User::getUserId, userLoginDTO.getUserId())
                        .one();
        // 判断用户名是否存在，如果不存在抛出业务异常提示
        if (Objects.isNull(user)) {
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 判断密码是否正确，如果不正确抛出业务异常提示
        if (!Objects.equals(user.getPassword(), userLoginDTO.getPassword())) {
            throw new BaseException(MessageConstant.PASSWORD_ERROR);
        }
        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        claims.put(JwtClaimsConstant.USERNAME, user.getNickname());
        claims.put(JwtClaimsConstant.NAME, user.getName());
        claims.put(JwtClaimsConstant.PHONE, user.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                                         jwtProperties.getUserTtl(),
                                         claims);
        log.info("用户登录成功生成token：{}", token);
        UserLoginVO userLoginVO = BeanUtil.copyProperties(user, UserLoginVO.class);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
